package com.zxl.working.utils;

import com.google.gson.Gson;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class CommUtil {

    private Logger logger = LogManager.getLogger(CommUtil.class);

    @Autowired
    private Gson gson;

    public String returnStr(int code,String msg,Object data){
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("code",code);
        resMap.put("msg",msg);
        resMap.put("data",data);

        return gson.toJson(resMap);
    }

    public String returnSuccess(Object data){
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("code",0);
        resMap.put("msg","请求成功");
        resMap.put("data",data);

        return gson.toJson(resMap);
    }

    public String returnFalse(Object data){
        Map<String,Object> resMap = new HashMap<>();
        resMap.put("code",-1);
        resMap.put("msg","请求失败");
        resMap.put("data",data);

        return gson.toJson(resMap);
    }

    public String getId(){
        String uuid = UUID.randomUUID().toString();
        logger.debug("uuid:"+uuid);
        StringBuffer hexString = new StringBuffer();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(uuid.getBytes());
            byte[] hash = md.digest();
            for (int i = 0; i < hash.length; i++) {
                if ((0xff & hash[i]) < 0x10) {
                    hexString.append("0" + Integer.toHexString((0xFF & hash[i])));
                } else {
                    hexString.append(Integer.toHexString(0xFF & hash[i]));
                }
            }
        }catch (Exception e){
            logger.error("获取ID错误",e);
        }
        return hexString.toString();
    }

    public String getDate(Date date,String timeFormat){
        String tf = StringUtils.isEmpty(timeFormat) ? "yyyy-MM-dd" : timeFormat;
        SimpleDateFormat sdf = new SimpleDateFormat(tf);
        return ObjectUtils.isEmpty(date) ? sdf.format(new Date()) : sdf.format(date);
    }
}
